import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as userActions from '../../store/actions/userAction'

// 装饰器
// 参1 把redux中的state数据 映射到 当前组件中的 props中
@connect(state => ({ users: state.users }), userActions)
class Index extends Component {

  state = {
    // 分页码
    page: 1
  }

  /* // 副作用
  static getDerivedStateFromProps(props,state){

  } */

  // 组件挂载完毕 生命周期方法
  componentDidMount() {
    let page = this.state.page
    this.setState({ page: ++this.state.page })
    this.props.getUsers()
  }

  componentWillUnmount() {
    this.props.clearStateUsers()
  }

  getUsersPage = () => {
    let page = this.state.page
    this.setState({ page: ++this.state.page })
    this.props.getUsersPage(page)
  }

  render() {
    return (
      <div>
        {
          this.props.users.length == 0 ? '加载中...' : (
            <>
              <ul>
                {
                  this.props.users.map((item, index) => {
                    return (
                      <li key={item._id}>
                        <span>{item.username}</span>
                      </li>
                    )
                  })
                }
              </ul>
              <div onClick={this.getUsersPage}>下一页</div>
            </>
          )
        }
      </div>
    )
  }
}

export default Index